//
//  BoundBankCardViewController.m
//  联付商圈
//
//  Created by 韩佳睿 on 2017/8/24.
//  Copyright © 2017年 lianfu. All rights reserved.
//

#import "BoundBankCardViewController.h"
#import "SHPlacePickerView.h"
#import "联付商圈-Swift.h"

@interface BoundBankCardViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *bankNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankTypeTextField;
@property (weak, nonatomic) IBOutlet UIButton *selectCityBtn;
@property (weak, nonatomic) IBOutlet UITextField *belongToBankTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (nonatomic, strong)SHPlacePickerView *shplacePicker;
@property (weak, nonatomic)NSString *cityString;

@end

@implementation BoundBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareTextField];
    
    self.navigationItem.title = @"绑定银行卡";
}

- (void)prepareTextField {
    self.bankNumberTextField.delegate = self;
    [self.bankNumberTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.bankTypeTextField.delegate = self;
    self.belongToBankTextField.delegate = self;
    self.phoneNumberTextField.delegate = self;
}

#pragma mark - TextField Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == _bankNumberTextField || textField ==  _phoneNumberTextField) {
        return [self validateNumber:string];
    } else {
        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == _phoneNumberTextField){
        [_phoneNumberTextField becomeFirstResponder];
    }else if (textField == _bankTypeTextField){
        [_bankTypeTextField becomeFirstResponder];
    }else if (textField == _bankNumberTextField){
        [_bankNumberTextField becomeFirstResponder];
    }else if (textField == _belongToBankTextField){
        [_belongToBankTextField becomeFirstResponder];
    }
    [self.shplacePicker removeFromSuperview];
}

#pragma mark - Action

- (IBAction)sureBoundBankAction:(id)sender {
    if (!([NSString isNilOrEmpty:_bankNumberTextField.text]||[NSString isNilOrEmpty:_bankTypeTextField.text]||[NSString isNilOrEmpty:_cityString]||[NSString isNilOrEmpty:_belongToBankTextField.text]||[NSString isNilOrEmpty:_phoneNumberTextField.text])) {
        NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
        
        NSDictionary *param = @{@"bankcardnumber" : _bankNumberTextField.text, @"bankresevedcall" : _phoneNumberTextField.text, @"bank" : _bankTypeTextField.text, @"name" : model.userName, @"provincesandcities" : _cityString, @"bankcardsubbranch" : _belongToBankTextField.text, @"type" : _bankTypeTextField.text};
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        
        [manager GET:[Host stringByAppendingString:@"addbank?"] parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            if (dic[@"success"] && [self isType:_bankTypeTextField.text]) {
                
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = dic[@"success"][@"message"];
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
                
                [self.navigationController popViewControllerAnimated:YES];
            } else if (dic[@"error"]) {
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = dic[@"error"][@"message"];
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
            } 
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
    } else {
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请填写完整信息";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
    }
}

- (IBAction)selectCityAction:(id)sender {
    
    
    [self dismissKeyboard];
    __weak BoundBankCardViewController *weakSelf= self;
    self.shplacePicker = [[SHPlacePickerView alloc] initWithIsRecordLocation:YES SendPlaceArray:^(NSArray *placeArray) {
        weakSelf.cityString = [NSString stringWithFormat:@"%@ %@ ",placeArray[0],placeArray[1]];
        [weakSelf.selectCityBtn setTitle:_cityString forState:UIControlStateNormal];
        [weakSelf.selectCityBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }];
    
    [self.view addSubview:self.shplacePicker];
}

#pragma mark - Bool
- (BOOL)validateNumber:(NSString*)number{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.bankNumberTextField) {
        if (textField.text.length > 25) {
            textField.text = [textField.text substringToIndex:25];
        }
    }
}

#pragma mark - Keyboard Show And Hide
- (void)keyboardWillHide:(NSNotification *)notification {
    [super keyboardWillHide:notification];
    CGRect frame = self.view.frame;
    frame.origin.y = 0;
    self.view.frame = frame;
}

- (void)dismissKeyboard {
    
    [_belongToBankTextField resignFirstResponder];
    [_bankNumberTextField resignFirstResponder];
    [_bankTypeTextField resignFirstResponder];
    [_belongToBankTextField resignFirstResponder];
}

- (BOOL)isType:(NSString *)str {
    if ([str isEqualToString:@"储蓄卡"]||[str isEqualToString:@"信用卡"]) {
        return YES;
    } else {
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"银行卡类型填写错误";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        return NO;
    }
}
@end
